//
//  YJOauthViewController.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/13.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit
import SVProgressHUD

class YJOauthViewController: UIViewController {
    
    deinit {
        JPrint(#function)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupNavigationBar()
        
        // 使用webView加载登陆界面
        // 登陆界面的url需要查看api文档
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
        
        // showWithStatus,需要主动关闭
        SVProgressHUD.show(withStatus: "正在加载...")
//        SVProgressHUD.show(withStatus: "正在加载", maskType: SVProgressHUDMaskType.none)
        
        // showInfoWithStatus,会自动关闭
        // SVProgressHUD.showInfoWithStatus("正在加载", maskType: SVProgressHUDMaskType.Clear)
        // SVProgressHUD.showErrorWithStatus("正在加载")
    }
    
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(autoFill))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(close))
    }
    
    // MARK: - UIAction
    
    @objc private func autoFill() {
        let jsCode = "document.getElementById('userId').value='13428283609';document.getElementById('passwd').value='syq'"
        webView.stringByEvaluatingJavaScript(from: jsCode);
    }
    
    @objc fileprivate func close() {
        dismiss(animated: true, completion: nil)
    }

    // MARK: - 懒加载
    private lazy var webView: UIWebView = UIWebView()

}

extension YJOauthViewController: UIWebViewDelegate {
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlStr = request.url!.absoluteString
        JPrint("urlString: \(urlStr)")
        
        // 点击取消: "http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330"
        
        // 点击授权: "http://www.baidu.com/?code=e67b175d1dff25aa630f0b1b74daa3f5"
        
        // 当点击了取消后授权后都会加载授权回调地址,所以判断如果是授权回调地址就表示点击的是 取消 或 授权
        // 不是授权回调地址,让他加载
        if !urlStr.hasPrefix(redirect_uri) {
            return true
        } else {
            // 加载的授权回调地址,说明点击的是 取消 或 授权
            // 获取参数
            // query: get请求?后面的参数
            let query = request.url!.query
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                // 点击的是 授权
                // "code=b2e409e0c79fa29dd9a3dc903f18ca73"
                // 截取query里面的code
                let queryStr = query! as NSString
                let code = queryStr.substring(from: codeString.characters.count)
                JPrint("code: \(code)")
                
                YJUserAccountViewModel.sharedInstance.loadAccessToken(code: code, completion: { (error) in
                    if error != nil {
                        JPrint("error: \(error)")
                        SVProgressHUD.showError(withStatus: "获取AccessToken失败")
                        
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double((Int64)(1 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: { 
                            self.close()
                        })
                        return
                    }
                    JPrint("没有错误关闭控制器")
                    self.close()
                    
                    // 切换控制器
                    AppDelegate.outSwitchRootViewController(YJWelcomeViewController())
                })
            } else {
                close()
            }
            return false
        }
    }
}
